#pragma once

#include <iostream>
#include <sys/epoll.h>
#include "nocopy.hpp"
#include "log.hpp"

class Epoller : public nocopy
{
    static const int size = 128;

public:
    Epoller()
    {
        _epfd = epoll_create(size);
        if (_epfd == -1)
        {
            log(Error, "epoll_create error: %s", strerror(errno));
        }
        else
        {
            log(Info, "epoll_create success: %d", _epfd);
        }
    }
    int EpollerWait(struct epoll_event revents[], int num)
    {
        int n = epoll_wait(_epfd, revents, num, _timeout);
        return n;
    }
    int EpollerUpdate(int op, int fd, uint32_t event)
    {
        int n = 0;
        if (op == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, op, fd, nullptr);
            if (n != 0)
            {
                log(Error, "epoll_ctl delete error!");
            }
        }
        else
        {
            struct epoll_event ep_event;
            ep_event.events = event;
            ep_event.data.fd = fd;
            n = epoll_ctl(_epfd, op, fd, &ep_event);
            if (n == 0)
            {
                log(Fatal, "epoll ctl success");
            }
            else
            {
                log(Fatal, "epoll ctl err");
            }
        }
        return n;
    }
    ~Epoller()
    {
        if (_epfd >= 0)
            close(_epfd);
    }

private:
    int _epfd;
    int _timeout = 3000;
};